package com.fingard.dsp.bank.directbank.rccosd01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @author Parker on 2019/7/19.
 * @version 1.0
 */
public class RCCOSD01BatPayRec extends RCCOSD01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {

        return d_QryBatPay(p_req1998);
    }

    /**
     * 批量待支付结果查询
     *
     * @param p_req1998
     * @return
     * @throws Exception
     */
    public RetAtsQryBatPayRec d_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;
        String p_FileName = p_req1998.reqHeader.reqSeqID + ".xls";
        String[] retStrArr = downloadFileFromBank(p_FileName, "QRCB017", p_req1998.reqHeader.transSeqID, p_req1998.reqHeader.reqSeqID);
        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            if (tmpBkReader != null) {
                if (tmpBkReader.getFirstText("/Message/Head/IBSReturnCode") != null) {
                    retAts.payInfoCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");//返回码;
                    retAts.respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");//返回信息
                    //下载共享目录批量查询文件
                    String downloadFilePath = trimEndFileSp(bankFront.bkTransFolder) + "/downloads/" + Format.Date10Format.format(new Date()) + "/";//共享目录
                    String p_FileFullPath = getTempFileDirectory() + "/downloads/" + Format.Date10Format.format(new Date());
                    StringBuilder p_sb = new StringBuilder();
                    if (SmbFileUtil.smbDownload(p_FileFullPath, downloadFilePath, p_FileName, p_sb) == 1) {
                        WriteBankLogLn("文件下载成功，位于：" + p_FileFullPath);
                        retAts.respCode = "0";
                        retAts.respInfo = "查询成功";
                        p_FileFullPath = StringHelper.trimEndFileSp(p_FileFullPath) + File.separator + p_FileName;
                        //解析Excel文件
                        RetAtsBatPayRecDetail retDetail = null;
                        FileInputStream fis = new FileInputStream(p_FileFullPath);
                        HSSFWorkbook hssfworkbook = new HSSFWorkbook(fis);
                        HSSFSheet worksheet = hssfworkbook.getSheetAt(0);
                        int rowNum = worksheet.getLastRowNum();
                        for (int i = 1; i <= rowNum; i++) {
                            retDetail = new RetAtsBatPayRecDetail();
                            if (StringHelper.hasAnyChar(worksheet.getRow(i).getCell(0).toString())) {
                                retDetail.payAct = worksheet.getRow(i).getCell(0).toString(); //支付账户
                            }
                            if (StringHelper.hasAnyChar(worksheet.getRow(i).getCell(1).toString())) {
                                retDetail.recAct = worksheet.getRow(i).getCell(1).toString(); //收款账户
                            }
                            if (StringHelper.hasAnyChar(worksheet.getRow(i).getCell(2).toString())) {
                                retDetail.recName = worksheet.getRow(i).getCell(2).toString(); //收款姓名
                            }
                            if (StringHelper.hasAnyChar(worksheet.getRow(i).getCell(3).toString())) {
                                retDetail.payAmount = worksheet.getRow(i).getCell(3).toString(); //支付金额
                            }
                            if (StringHelper.hasAnyChar(worksheet.getRow(i).getCell(4).toString())) {
                                retDetail.payInfoCode = worksheet.getRow(i).getCell(4).toString(); //支付信息
                            }
                            if (StringHelper.hasAnyChar(worksheet.getRow(i).getCell(4).toString())) {
                                retDetail.result = worksheet.getRow(i).getCell(4).toString();//支付结果
                            }
                            if (StringHelper.hasAnyChar(worksheet.getRow(i).getCell(5).toString())) {
                                retDetail.postScript = worksheet.getRow(i).getCell(5).toString();//对账码
                            }
                            retAts.writeRetDetail(retDetail);
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = p_sb.toString();
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "银行返回信息有误";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "银行返回数据为空";
            }
        } else if (retStrArr[0].equals(ConnState.FAIL)) {
            retAts.respCode = "-1";
            retAts.respInfo = retStrArr[1];
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = retStrArr[1];
        }
        retAts.writeAfterDetail();
        return retAts;
    }


    /**
     * 批量待支付
     *
     * @param p_reqBat
     * @return
     * @throws Exception
     */
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.writeStart();
        FileOutputStream fos = null;
        String payAct = p_reqBat.ownAct;// 付方账号，映射核心客户号所用
        String p_FileName = p_reqBat.reqHeader.reqSeqID + ".xls";
        String tmpFilePath = getTempFileDirectory() + "/uploads/" + Format.Date10Format.format(new Date());
        String p_FileFullPath = tmpFilePath + File.separator + p_FileName;
        try {
            //生成代付Excel文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Sheet1");
            HSSFRow row = sheet.createRow(0);
            row.createCell(0).setCellValue("付款账号");
            row.createCell(1).setCellValue("收款账号");
            row.createCell(2).setCellValue("收款人名称");
            row.createCell(3).setCellValue("金额");
            row.createCell(4).setCellValue("账户类型(P折C卡)");
            row.createCell(5).setCellValue("预留字段1");
            row.createCell(6).setCellValue("预留字段2");

            //写入数据
            int i = 1;
            while (p_reqBat.readRecord()) {
                String tmpCertType = "1".equals(p_reqBat.readedDetail.certType) ? "P" : "C";
                row = sheet.createRow(i++);
                row.createCell(0).setCellValue(p_reqBat.readedDetail.payAct);
                row.createCell(1).setCellValue(p_reqBat.readedDetail.recAct);
                row.createCell(2).setCellValue(p_reqBat.readedDetail.recName);
                row.createCell(3).setCellValue(p_reqBat.readedDetail.payAmount);
                row.createCell(4).setCellValue(tmpCertType);
                row.createCell(5).setCellValue(p_reqBat.readedDetail.purpose);
                row.createCell(6).setCellValue(p_reqBat.readedDetail.askNumber);
            }

            WriteBankLogLn("批量代付生成Excel文件本地路径:" + p_FileFullPath);
            if (!FileHelper.existFile(tmpFilePath)) {
                FileHelper.mkdir(tmpFilePath);
            }
            fos = new FileOutputStream(p_FileFullPath);
            workbook.write(fos);
            WriteBankLogLn("批量代付生成Excel文件保存成功!");
            fos.close();
        } catch (Exception e) {
            WriteBankLogLn("生成批付Excel文件失败，返回异常信息：" + e.getMessage());
            retAts.respCode = "-1";
            retAts.respInfo = "生成批付Excel文件失败，返回异常信息：" + e.getMessage();
            retAts.transState = PaymentState.FAIL_Batch;
            retAts.payInfoCode = PaymentState.FAIL_Batch;
            retAts.writeRetToATS();
            return retAts;
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
        //上传文件到前置机目录
        if (FileHelper.existFile(p_FileFullPath)) {
            String remotePath = trimEndFileSp(bankFront.bkTransFolder) + "/uploads/";
            int result = SmbFileUtil.smbUploading(p_FileFullPath, "", remotePath);
            if (result == -1) {
                retAts.respCode = "-1";
                retAts.respInfo = "上传文件到前置机目录异常";
                retAts.writeRetToATS();
                return retAts;
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "批付Excel文件不存在";
            retAts.writeRetToATS();
            return retAts;
        }
        String[] retStrArr = new String[]{};
        if ("198801".equals(p_reqBat.reqHeader.commandCode)) {
            retStrArr = uploadFileToBank(p_FileName, "QRCB015", p_reqBat.reqHeader.reqSeqID, "198801", "");
        } else if ("198802".equals(p_reqBat.reqHeader.commandCode)) {
            retStrArr = uploadFileToBank(p_FileName, "QRCB016", p_reqBat.reqHeader.reqSeqID, "198802", "");
        } else if ("198803".equals(p_reqBat.reqHeader.commandCode)) {
            retStrArr = uploadFileToBank(p_FileName, "QRCB021", p_reqBat.reqHeader.reqSeqID, "198803", payAct);
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "指令代码不存在";
            retAts.writeRetToATS();
            return retAts;
        }
        // String[] retStrArr = uploadFileToBank(p_FileName, "198801".equals(p_reqBat.reqHeader.commandCode) ? "QRCB015" : "QRCB016", p_reqBat.reqHeader.reqSeqID);
        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            if (tmpBkReader != null) {
                if (tmpBkReader.getFirstText("/Message/Head/IBSReturnCode") != null) {
                    retAts.transState = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");//返回码;
                    retAts.payInfoCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");//返回码;
                    retAts.respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");//返回信息
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "银行返回信息有误";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "银行返回数据为空";
            }
        } else if (retStrArr[0].equals(ConnState.FAIL)) {
            retAts.respCode = "-1";
            retAts.respInfo = retStrArr[1];
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = retStrArr[1];
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {

        return null;
    }
}
